<?

/*
 * Database interaction helper functions.
 */ 
class db_Schema {
    static $schema_cache = array();
    
    static function get($name) {
        if (array_key_exists($name, self::$schema_cache)) {
            return self::$schema_cache[$name];
        }

        $scm = new db_Schema($name);
        self::$schema_cache[$name] = $scm;

        return $scm;
    }

    function __construct($name) {
        $r = mysql_query("DESCRIBE $name;");
        if (! $r) {
            throw new Exception("Can't get schema for table '$name'.");
        }

        $this->cols = array();
        while ($col = mysql_fetch_object($r)) {
            // don't much like the mysql name format, so convert
            $a = array('name' => $col->Field, 'type' => $col->Type);
            array_push($this->cols, (object)$a);
        }
    }

    function name() {
        return $this->name;
    }

    function col_by_idx($idx) {
        return $this->cols[$idx];
    }

    function idx_by_name($name) {
        for ($i=0; $i<sizeof($this->cols); $i++) {
            if ($this->cols[$i]->name == $name) {
                return $i;
            }
        }
        return false;
    }

    function column_names() {
        $r = array();
        foreach ($this->cols as $k => $v) {
            array_push($r, $v->name);
        }
        return $r;
    }
}

?>